package cn.cnsy123.shorturls.business.service.impl;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.cnsy123.shorturls.api.controller.param.LoginRequestParam;
import cn.cnsy123.shorturls.api.controller.vo.SysLoginResult;
import cn.cnsy123.shorturls.business.encoder.PasswordEncoder;
import cn.cnsy123.shorturls.business.entity.SysUserInfo;
import cn.cnsy123.shorturls.business.entity.SysUserLoginInfo;
import cn.cnsy123.shorturls.business.exception.BusinessException;
import cn.cnsy123.shorturls.business.localuser.ConsoleUserVo;
import cn.cnsy123.shorturls.business.mapper.SysUserInfoMapper;
import cn.cnsy123.shorturls.business.mapper.SysUserLoginInfoMapper;
import cn.cnsy123.shorturls.business.service.SysUserLoginInfoService;
import cn.cnsy123.shorturls.business.service.SysUserLoginLogService;
import cn.cnsy123.shorturls.business.util.UserAgentUtil;
import cn.cnsy123.shorturls.constants.CommonConstants;
import cn.cnsy123.shorturls.constants.SessionInfoConstants;
import cz.mallat.uasparser.UserAgentInfo;
@Service(value = "sysUserLoginInfoService")
public class SysUserLoginInfoServiceImpl implements SysUserLoginInfoService {
    
    @Autowired
    private SysUserLoginInfoMapper sysUserLoginInfoMapper;
    
    @Autowired
    private SysUserInfoMapper sysUserInfoMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private SysUserLoginLogService sysUserLoginLogService;

    @Override
    @Transactional(readOnly = false,propagation = Propagation.REQUIRED,rollbackFor = BusinessException.class)
    public SysLoginResult loginProcess(LoginRequestParam loginRequestParam,HttpServletRequest request,HttpServletResponse response) {
        SysLoginResult sysLoginResult = new SysLoginResult(100, "登录请求失败！");
        try {
            SysUserLoginInfo sysUserLoginInfo = sysUserLoginInfoMapper.selectByUsername(loginRequestParam.getUsername());
            if(sysUserLoginInfo != null) {
                Boolean accountStatus = sysUserLoginInfo.getAccountStatus();
                if(accountStatus.booleanValue()) {
                    sysLoginResult = new SysLoginResult(100, "请求账户被锁定了！");
                }else {
                    String password = sysUserLoginInfo.getPassword();
                    boolean flag = passwordEncoder.matches(loginRequestParam.getPassword(), password);
                    if(flag) {
                        sysLoginResult = new SysLoginResult(200, "登录请求成功！");
                        SysUserInfo sysUserInfo = sysUserInfoMapper.selectByPrimaryKey(sysUserLoginInfo.getUserId());
                        ConsoleUserVo userVo = new ConsoleUserVo(sysUserLoginInfo.getUserId(),sysUserLoginInfo.getUserName(),sysUserInfo.getRealName());
                        request.getSession().setAttribute(SessionInfoConstants.SESSION_USER_BEAN, userVo);
                        UserAgentInfo userAgentInfo = UserAgentUtil.getCurrentRequestHeader(request.getHeader("User-Agent"));
                        String loginIp = UserAgentUtil.getIpAddress(request);
                        String deviceType = userAgentInfo.getDeviceType();
                        String browserName = userAgentInfo.getUaFamily();
                        sysUserLoginLogService.saveUserLoginLog(sysUserLoginInfo.getUserName(), sysUserInfo.getRealName(), loginIp, deviceType, browserName, new Date(System.currentTimeMillis()));
                        if("1".equals(loginRequestParam.getRememberAccount())) {
                            StringBuffer cookieUser = new StringBuffer();
                            cookieUser.append(Base64.encodeBase64String(loginRequestParam.getUsername().getBytes("UTF-8")));
                            cookieUser.append("#_#");
                            cookieUser.append(Base64.encodeBase64String(loginRequestParam.getPassword().getBytes("UTF-8")));
                            
                            Cookie cookie = new Cookie(CommonConstants.COOKIE_REMEMBER, cookieUser.toString());
                            //cookie.setHttpOnly(true);
                            cookie.setPath("/");
                            cookie.setVersion(1);
                            cookie.setMaxAge(60 * 60 * 24 * 7);
                            response.addCookie(cookie);
                        }
                        
                    }else {
                        sysLoginResult = new SysLoginResult(100, "密码输入错误！");
                    }
                }
            } else {
                sysLoginResult = new SysLoginResult(100, "请求账户不存在！");
            }
        } catch (Exception e) {
            throw new BusinessException(e);
        }
        return sysLoginResult;
    }

}
